import type { IDraggable, IRect, Vertex2D } from '../core/types'
import { MathUtils } from './MathUtils'

export class MatrixUtils {
  static calculateRotatedCorners(rect: IRect): Vertex2D[] {
    // 解构参数
    const { x, y, w, h, rotate } = rect
    const width = w
    const height = h

    // 计算旋转中心点（矩形的中心点）
    const centerX = x + width / 2
    const centerY = y + height / 2
    // 定义四个顶点相对于中心点的位置（未旋转时）
    const corners = [
      { x: -width / 2, y: -height / 2 }, // 左上
      { x: width / 2, y: -height / 2 }, // 右上
      { x: width / 2, y: height / 2 }, // 右下
      { x: -width / 2, y: height / 2 }, // 左下
    ] as const // 使用as const确保类型为readonly

    // 计算旋转后的顶点坐标
    return corners.map(corner => {
      // 应用旋转矩阵
      const rotatedX =
        corner.x * MathUtils.cos(rotate) - corner.y * MathUtils.sin(rotate)
      const rotatedY =
        corner.x * MathUtils.sin(rotate) + corner.y * MathUtils.cos(rotate)

      // 转换回全局坐标系统
      return {
        x: rotatedX + centerX,
        y: rotatedY + centerY,
      }
    })
  }

  static calculateBounds(rect: IDraggable): number[] {
    const arr = MatrixUtils.calculateRotatedCorners(rect)
    let minX = arr[0].x
    let minY = arr[0].y
    let maxX = arr[0].x
    let maxY = arr[0].y

    for (const point of arr) {
      if (point.x < minX) minX = point.x
      if (point.y < minY) minY = point.y
      if (point.x > maxX) maxX = point.x
      if (point.y > maxY) maxY = point.y
    }

    return [minX, minY, maxX, maxY]
  }

  static rotatePoint(x: number, y: number, angle: number) {
    const radian = (Math.PI / 180) * angle
    const cos = Math.cos(radian)
    const sin = Math.sin(radian)
    const nx = cos * x + sin * y
    const ny = cos * y - sin * x
    return { x: nx, y: ny }
  }
}
